package com.ErpCoreWeb.Desktop;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.UUID;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper;

import com.ErpCoreWeb.Common.Global;
/**
 * Servlet implementation class SelectBG
 */
@WebServlet("/SelectBG")
public class SelectBG extends HttpServlet {
	private static final long serialVersionUID = 1L;

	HttpServletRequest request;
	HttpServletResponse response;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SelectBG() {
        super();
        // TODO Auto-generated constructor stub
    }

    //初始化变量
    void initData()
    {
        if (request.getSession().getAttribute("User") == null)
        {
            try {
				response.sendRedirect("../Login.jsp");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            return ;
        }
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doProc(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doProc(request,response);
	}
	void doProc(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{

		this.request=request;
		this.response=response;

		response.setContentType("text/html;charset=UTF-8");
		request.setCharacterEncoding("UTF-8");

		//初始化变量
	    initData();
	    //
        MultiPartRequestWrapper wrapper = (MultiPartRequestWrapper) request; 
        String Action = wrapper.getParameter("Action");
        if (Action == null) Action = "";

        if (Action.equalsIgnoreCase("PostData"))
        {
            PostData();
            return ;
        }
	}
    void PostData()
    {
    	try { 
    		String sPath = String.format("%s/DesktopImg/", Global.GetDesktopIconPathName());
        	sPath = request.getSession().getServletContext().getRealPath(sPath);
	        File fi=new File(sPath);
	        if (!fi.exists())
	        	fi.mkdir();
	        
	        MultiPartRequestWrapper wrapper = (MultiPartRequestWrapper) request; 
	        String fileName = wrapper.getFileNames("fileIcon")[0]; 
	        File file = wrapper.getFiles("fileIcon")[0]; 
	        
	        int idx = fileName.lastIndexOf('.');
	        if (idx > -1)
	        {
	            String sExt = fileName.substring(idx);
	            sExt = sExt.toLowerCase();
	            if (!sExt.equalsIgnoreCase(".jpg") && !sExt.equalsIgnoreCase(".png") && !sExt.equalsIgnoreCase(".gif"))
	            {
	            	response.getWriter().print("<script>parent.callback('仅支持jpg,png,gif图片文件！')</script>");
	                return;
	            }
	            String sFileName = UUID.randomUUID().toString() + sExt;
	            String sFile = sPath + sFileName;
	            byte[] buffer = new byte[1024];
	            FileOutputStream fos = new FileOutputStream(sFile); 
	            InputStream in = new FileInputStream(file); 
	            try { 
	            	int num = 0; 
	            	while ((num = in.read(buffer)) > 0) {
	            		fos.write(buffer, 0, num);
	            	}
				} catch (Exception e) { 
					e.printStackTrace(System.err);
				} finally { 
					in.close(); 
					fos.close(); 
				}
	
	            response.getWriter().print("<script>parent.callback('')</script>");
	        }
	        else
	        {
	        	response.getWriter().print("<script>parent.callback('请选择图片文件！')</script>");
	            return;
	        }
    	} catch (Exception e) { 
			e.printStackTrace(System.err);
		}

    }
}
